<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Utils\ResponseResult\JsonResult;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;

class RoleController extends Controller
{
    //
    public function list(Request $request){
        $role_name=$request->input('role_name');
        $per_page=$request->input('per_page',env('DEFAULT_PAGE',10));
        $list=DB::table("roles")
            ->where(function($query) use($role_name){
                if($role_name!==null){
                    $query->where('role_name','like','%'.$role_name.'%');
                }
            })
            ->paginate($per_page)
            ->withQueryString();
        return JsonResult::success($list,"获取角色列表成功");
    }
    public function create(Request $request){
        //验证请求
        $rules=[
            "role_name" => "required",
            "permissions" => "required"
        ];
        if(Validator::make($request->all(),$rules)->fails()){
            return JsonResult::forbidden(null,"请求参数错误");
        }
        //创建角色
        $insertID=DB::table("roles")->insertGetId($request->all());
        if($insertID>0){
            return JsonResult::success(null,"创建角色成功");
        }
        return JsonResult::forbidden(null,"创建角色失败");
    }
    public function edit(Request $request){
        //验证请求
        $rules=[
            "id" => "required",
            "role_name" => "required",
            "permissions" => "required"
        ];
        if(Validator::make($request->all(),$rules)->fails()){
            return JsonResult::forbidden(null,"请求参数错误");
        }
        //编辑角色
        $id=$request->input("id");
        $data=$request->except("id");
        DB::table("roles")->where("id",$id)->update($data);
        return JsonResult::success(null,"编辑角色成功");
    }
    public function delete(Request $request){
        //验证请求
        $rules=["ids" => "required"];
        if(Validator::make($request->all(),$rules)->fails()){
            return JsonResult::forbidden(null,"请求参数错误");
        }
        //删除角色
        $ids=$request->input("ids");
        $idsArr=explode(",",$ids);
        DB::table("roles")->whereIn("id",$idsArr)->delete();

        return JsonResult::success(null,"删除角色成功");
    }


}
